<?php
require (PLUGIN_SPHINX);
class Search extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('society_model', '', TRUE);
       	$this->load->model('news_model', '', TRUE);
       	$this->load->model('announcement_model', '', TRUE);
       	$this->load->model('knowledge_model', '', TRUE);
    }
    
    function ajax_search() {
    	$keywords = urldecode($this->input->post("keywords"));
        $search_category = $this->input->post("search_category");
        $search_type = $this->input->post("search_type");
        
    	$validate_data['keywords'] = $keywords;
    	if (!$this->_ajax_validate($validate_data)) { return ; }
        
        $cl = new SphinxClient ();
		$cl->SetArrayResult(true);
		$cl->SetFilter("is_published", array(IS_PUBLISHED));
		$cl->SetSortMode(SPH_SORT_ATTR_DESC, "create_time");
		
		if (!empty($search_category)) {
			$cl->SetFilter("category_id", array($search_category));
		}
		
    	if (!empty($search_type)) {
			$cl->SetFilter("type", array($search_type));
		}
		
		//查询内容 + 查询索引名称
		$temp_data = $cl->Query($keywords, "*");
		//echo "<pre>";
		//print_r($temp_data);
		//return ;
		
        if ($temp_data['total'] == 0) {
        	$this->output->set_output(json_encode('null_result'));
        } else {
        	$loop_times = ($temp_data['total'] < 10) ? $temp_data['total'] : 9;
        	for ($i = 0; $i < $loop_times; $i++) {
        		$id_array[] = $temp_data['matches'][$i]['id'];
        	}
        	
        	foreach ($id_array as $k => $v) {
        		if ($temp_data['matches'][$k]['attrs']['type'] == NEWS_TYPE) {
	        		$detail_data[$k] = $this->news_model->get_by_id($v, 'id, title, category_id');
	        		$detail_data[$k]['type'] = NEWS_TYPE;
        		} else {
        			$detail_data[] = $this->announcement_model->get_by_id($v, 'id, title, category_id');
        			$detail_data[$k]['type'] = ANNOUNCEMENT_TYPE;
        		}
        	}
        	
        	$data['details'] = $detail_data;
        	
        	foreach ($temp_data['words'] as $k => $v) {
        		$keywords_array[] = $k;
        	}
        	$data['keywords_str'] = implode('_', $keywords_array);
        	
        	$data['time'] = $temp_data['time'];
       		$data['total'] = $temp_data['total'];
       		
        	$this->output->set_output(json_encode($data));
        }
    }
}